package com.yy.wga.goods.service.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.wga.common.core.dto.BaseRequestDTO;
import com.yy.wga.common.core.enmus.EResponseCode;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.common.util.mapping.BeansUtils;
import com.yy.wga.common.web.intereceptor.RequestHolder;
import com.yy.wga.goods.feign.response.BuyGoodsCreateOrderResponse;
import com.yy.wga.goods.feign.response.QueryGoodsPayResultResponse;
import com.yy.wga.goods.service.entity.pojo.GoodsUpGradeDO;
import com.yy.wga.goods.service.service.GoodsUpGradeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.validation.Valid;

/**
 * @Author: gc
 * @Date: 2024/12/21
 * @Description:
 **/
@Component
@RequiredArgsConstructor
public class GoodsUpGradeManager {

    private final GoodsUpGradeService goodsUpGradeService;
    private final OrderUpGradeService orderUpGradeService;
    private final OrderDeliveryAddressService orderDeliveryAddressService;
    private final PayManager payManager;

    public BuyGoodsCreateOrderResponse createOrder(BuyGoodsCreateOrderRequest request) {
        GoodsUpGradeDO goodsUpGrade = goodsUpGradeService.getOne(new LambdaQueryWrapper<GoodsUpGradeDO>()
                .eq(GoodsUpGradeDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .eq(GoodsUpGradeDO::getId, request.getId()));
        if (goodsUpGrade == null) {
            throw new BusinessException("商品不存在");
        }
        // 保存订单
        UserCacheDTO userCache = RequestUserHolder.getUserCache();
        OrderUpGradeDO orderUpGrade = BeansUtils.map(goodsUpGrade, OrderUpGradeDO.class);
        orderUpGrade.setGoodsId(goodsUpGrade.getId());
        orderUpGrade.setOrderNo(IdUtils.uuid());
        orderUpGrade.setUserId(userCache.getUserId());
        orderUpGrade.setStatus(1);
        orderUpGrade.setPrice(goodsUpGrade.getFinalPrice());
        orderUpGrade.setId(null);
        // 复购价格和佣金不同
        if (userCache.getGrade() > goodsUpGrade.getUpGrade()) {
            if (userCache.getGrade().equals(EUserGrade.SHARE_3.getType())) {
                orderUpGrade.setPrice(goodsUpGrade.getShareRepurchaseFinalPrice());
                orderUpGrade.setCommissionValue(goodsUpGrade.getShareRepurchaseCommissionValue());
            } else {
                orderUpGrade.setPrice(goodsUpGrade.getServerRepurchaseFinalPrice());
                orderUpGrade.setCommissionValue(goodsUpGrade.getServerRepurchaseCommissionValue());
            }
            orderUpGrade.setUpAwardValue(0);
        }
        if (userCache.getGrade().equals(goodsUpGrade.getUpGrade())
                && userCache.getLevel() >= goodsUpGrade.getUpGradeLevel()) {
            if (userCache.getGrade().equals(EUserGrade.SHARE_3.getType())) {
                orderUpGrade.setPrice(goodsUpGrade.getShareRepurchaseFinalPrice());
                orderUpGrade.setCommissionValue(goodsUpGrade.getShareRepurchaseCommissionValue());
            } else {
                orderUpGrade.setPrice(goodsUpGrade.getServerRepurchaseFinalPrice());
                orderUpGrade.setCommissionValue(goodsUpGrade.getServerRepurchaseCommissionValue());
            }
            orderUpGrade.setUpAwardValue(0);
        }
        orderUpGradeService.save(orderUpGrade);

        // 保存收获地址
        OrderDeliveryAddressDO addressDO = BeansUtils.map(request.getDeliveryAddress(), OrderDeliveryAddressDO.class);
        addressDO.setAppKey(RequestUserHolder.getBaseRequest().getAppKey());
        addressDO.setOrderNo(orderUpGrade.getOrderNo());
        orderDeliveryAddressService.save(addressDO);

        // 创建预支付订单
        CreatePrePayOrderRequest createPrePayOrderRequest = new CreatePrePayOrderRequest();
        createPrePayOrderRequest.setAmount(orderUpGrade.getPrice());
        createPrePayOrderRequest.setOutTradeNo(orderUpGrade.getOrderNo());
        createPrePayOrderRequest.setSubject("微信大联盟下单");
        createPrePayOrderRequest.setDescription(orderUpGrade.getTitle());
        createPrePayOrderRequest.setPayChannel(1);
        createPrePayOrderRequest.setPayType(1);
        createPrePayOrderRequest.setUserId(userCache.getUserId());
        createPrePayOrderRequest.setOpenId(userCache.getOpenId());
        createPrePayOrderRequest.setType(1);
        createPrePayOrderRequest.setSysType(RequestUserHolder.getBaseRequest().getSysType());
        CreatePrePayOrderResponse payOrderResponse = payManager.createPreOrder(createPrePayOrderRequest);

        // 保存支付订单号
        OrderUpGradeDO updateOrder = new OrderUpGradeDO();
        updateOrder.setId(orderUpGrade.getId());
        updateOrder.setPayOrderNo(payOrderResponse.getPayOrderNo());
        orderUpGradeService.updateById(updateOrder);

        // 返回支付信息
        BuyGoodsCreateOrderResponse response = new BuyGoodsCreateOrderResponse();
        response.setJsWechatPayData(BeansUtils.map(payOrderResponse.getJsWechatPayData(), BuyGoodsCreateOrderResponse.JsWechatPayData.class));
        response.setOrderNo(orderUpGrade.getOrderNo());
        return response;
    }

    /**
     * 查询支付结果
     * @param request
     * @return
     */
    public QueryGoodsPayResultResponse queryPayResult(@Valid QueryGoodsPayResultRequest request) {
        // 查询商品订单
        UserCacheDTO userCache = RequestUserHolder.getUserCache();
        BaseRequestDTO baseRequestDTO = RequestHolder.getBaseRequest();
        OrderUpGradeDO orderUpGradeDO = orderUpGradeService.getOne(new LambdaQueryWrapper<OrderUpGradeDO>()
                .eq(OrderUpGradeDO::getAppKey, baseRequestDTO.getAppKey())
                .eq(OrderUpGradeDO::getUserId, userCache.getUserId())
                .eq(OrderUpGradeDO::getOrderNo, request.getOrderNo()));
        if (orderUpGradeDO == null) {
            throw new BusinessException(EResponseCode.SYSTEM_RECORD_NOT_EXIST);
        }

        // 返回
        QueryGoodsPayResultResponse response = new QueryGoodsPayResultResponse();
        response.setStatus(orderUpGradeDO.getStatus().equals(7) || orderUpGradeDO.getStatus().equals(3) ? 2 : 1);
        return response;
    }
}
